package cn.com.k2data.docx4j;


import org.docx4j.Docx4J;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.*;

import java.math.BigInteger;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Example {

  public static void main(String[] args) throws Exception {


    String[][] datas = {
        {"风资源参数	", "	金风109/2500机组设计风况参数	", "	内蒙古白旗项目风电场参数"},
        {"年平均空气密度ρ（kg/m3）	", "	1.225	", "	1.031"},
        {"50年一遇极限风速V50（10min平均值）（m/s）	", "	42.5	", "	48.53"},
        {"50年一遇极限风速Ve50（3s平均值）（m/s）	", "	59.5	", "	63.09"},
        {"年平均风速Vave（m/s）	", "	8.5	", "	10.28"},
        {"威布尔尺度因子A	", "	瑞利分布	", "	11.59"},
        {"威布尔形状因子K	", "	瑞利分布	", "	1.996"},
        {"湍流强度特征值I15	", "	0.18	", "	0.125"},
        {"风剪切指数α	", "	0.2	", "	0.12"},
        {"入流角（deg）	", "	8	", "	6.9"},
        {"轮毂高度（m）	", "	90	", "	80"}
    };


    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart mdp = wordMLPackage.getMainDocumentPart();

    ObjectFactory factory = Context.getWmlObjectFactory();
    Tbl table = createTable(datas);
    withBorders(table);

//    Tr tr = factory.createTr();
//    P paragraphOfText = wordMLPackage.getMainDocumentPart().createParagraphOfText("Field 1");
//    addTableCell(tr, paragraphOfText, factory);
//    table.getContent().add(tr);


    mdp.addObject(table);

    withBorders(table)
    mdp.addObject(createTable(datas));

    mdp.addParagraphOfText("hello world");
//
//    ProtectDocument protection = new ProtectDocument(wordMLPackage);
//    protection.restrictEditing(STDocProtect.READ_ONLY, "foobaa");


    String filename = "protect.docx";
    Docx4J.save(wordMLPackage, new java.io.File(filename), Docx4J.FLAG_SAVE_ZIP_FILE);

    // To save encrypted, you'd use FLAG_SAVE_ENCRYPTED_AGILE, for example:
    // Docx4J.save(wordMLPackage, new java.io.File(filename), Docx4J.FLAG_SAVE_ENCRYPTED_AGILE, "foo");


    System.out.println("Saved " + filename);

  }

  /**
   * 用给定的段落作为内容向给定的行中添加一个单元格.
   *
   * @param tr
   * @param paragraph
   */
  private static void addTableCell(Tr tr, P paragraph, ObjectFactory factory) {
    Tc tc1 = factory.createTc();
    tc1.getContent().add(paragraph);
    tr.getContent().add(tc1);
  }

  /**
   * 给表格添加简单的黑色边框.
   *
   * @param table
   */
  private static Tbl withBorders(Tbl table) {
    table.setTblPr(new TblPr());
    CTBorder border = new CTBorder();
    border.setColor("auto");
    border.setSz(new BigInteger("4"));
    border.setSpace(new BigInteger("0"));
    border.setVal(STBorder.SINGLE);

    TblBorders borders = new TblBorders();
    borders.setBottom(border);
    borders.setLeft(border);
    borders.setRight(border);
    borders.setTop(border);
    borders.setInsideH(border);
    borders.setInsideV(border);
    table.getTblPr().setTblBorders(borders);
    return table;
  }


  private static Tbl createTable(int row, int column) {
    ObjectFactory factory = Context.getWmlObjectFactory();
    Tbl table = factory.createTbl();
    Function<Integer, List<Tr>> initTrFunction = number -> IntStream.range(0, number)
        .mapToObj(value -> factory.createTr())
        .collect(Collectors.toList());

    Function<Integer, List<Tc>> initTcFunction = number -> IntStream.range(0, number)
        .mapToObj(value -> factory.createTc())
        .collect(Collectors.toList());

    initTrFunction.apply(row)
        .stream()
        .peek(tr -> initTcFunction.apply(column)
            .forEach(tc -> tr.getContent().add(tc))
        ).forEach(tr -> table.getContent().add(tr));
    return table;

  }


  private static Tbl createTable(String[][] data) {
    ObjectFactory factory = Context.getWmlObjectFactory();
    Tbl table = factory.createTbl();

    Function<String[], List<Tc>> tcFunction = tcData -> Stream.of(tcData)
        .map(value -> {
          Tc tc = factory.createTc();
          tc.getContent().add(createparagraphOfText(value));
          return tc;
        })
        .collect(Collectors.toList());

    Function<String[][], List<Tr>> trFunction = trData -> Stream.of(trData)
        .map(strings -> {
          Tr tr = factory.createTr();

          tcFunction.apply(strings)
              .forEach(tc -> tr.getContent().add(tc));
          return tr;
        }).collect(Collectors.toList());


    trFunction.apply(data)
        .forEach(tr -> table.getContent().add(tr));
    return table;

  }

  public static P createparagraphOfText(String simpleText) {
    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.P para = factory.createP();

    if (simpleText != null) {
      org.docx4j.wml.Text t = factory.createText();
      t.setValue(simpleText);

      org.docx4j.wml.R run = factory.createR();
      run.getContent().add(t); // ContentAccessor

      para.getContent().add(run); // ContentAccessor
    }
    return para;
  }


}
